<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #billTypeSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择单据类型" @search="billTypeOpen" />
      </template>
      <template #warehouseSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择仓库名称" @search="warehouseOpen" />
      </template>
      <template #customerSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择客户名称" @search="customerOpen" />
      </template>
      <template #receivingOrganizationSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择收货组织名称" @search="organizationOpen" />
      </template>
      <template #supplierSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择供应商名称" @search="supplierOpen" />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="调拨入库明细" key="busMiscellaneousStorageItem" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="busMiscellaneousStorageItem"
          :loading="busMiscellaneousStorageItemTable.loading"
          :columns="busMiscellaneousStorageItemTable.columns"
          :dataSource="busMiscellaneousStorageItemTable.dataSource"
          :height="340"
          :rowNum="true"
          rowNumKey="rowNum"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        >
          <template #materialSlot="props">
            <a-input-search @search="handleView(props)" placeholder="请选择料品编码" v-model:value="props.row.materialCode"></a-input-search>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 单据类型 -->
  <billTypeSelectModel @register="billTypeRegModal" @getSelectResult="billTypehandleSuccess" v-bind="getBindValue"></billTypeSelectModel>
  <!-- 仓库 -->
  <warehouseSelectModel @register="warehouseRegModal" @getSelectResult="warehousehandleSuccess" v-bind="getBindValue"></warehouseSelectModel>
  <!-- 客户 -->
  <customerSelectModel @register="customerRegModal" @getSelectResult="customerhandleSuccess" v-bind="getBindValue"></customerSelectModel>
  <!-- 供应商 -->
  <supplierSelectModel @register="supplierRegModal" @getSelectResult="supplierhandleSuccess" v-bind="getBindValue"></supplierSelectModel>
  <!-- 收货组织 -->
  <organizationSelectModel
    @register="organizationRegModal"
    @getSelectResult="organizationhandleSuccess"
    v-bind="getBindValue"
  ></organizationSelectModel>
  <!-- 料品 -->
  <materialSelectModel @register="materialRegModal" @getSelectResult="materialhandleSuccess" v-bind="getBindValue"></materialSelectModel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import { formSchema, busMiscellaneousStorageItemColumns } from '../BusTransferStorage.data';
import { saveOrUpdate, busMiscellaneousStorageItemList } from '../BusTransferStorage.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import billTypeSelectModel from '/@/views/components/billTypeSelectModel.vue';
import warehouseSelectModel from '/@/views/components/warehouseSelectModel.vue';
import organizationSelectModel from '/@/views/components/organizationSelectModel.vue';
import supplierSelectModel from '/@/views/components/supplierSelectModel.vue';
import customerSelectModel from '/@/views/components/customerSelectModel.vue';
import materialSelectModel from '/@/views/components/materialSelectModel.vue';
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const formDisabled = ref(false);
const refKeys = ref(['busMiscellaneousStorageItem']);
const activeKey = ref('busMiscellaneousStorageItem');
const busMiscellaneousStorageItem = ref();
const tableRefs = { busMiscellaneousStorageItem };
const busMiscellaneousStorageItemTable = reactive({
  loading: false,
  dataSource: [],
  columns: busMiscellaneousStorageItemColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(busMiscellaneousStorageItemList, { id: data?.record?.id }, busMiscellaneousStorageItemTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'busMiscellaneousStorageItem';
  busMiscellaneousStorageItemTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    busTransferStorageItemList: allValues.tablesValue[0].tableData,
  };
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
const getBindValue = Object.assign({}, '');
const [billTypeRegModal, { openModal: openBillTypeModal }] = useModal();
const [warehouseRegModal, { openModal: openWarehouseModal }] = useModal();
const [customerRegModal, { openModal: openCustomerModal }] = useModal();
const [supplierRegModal, { openModal: openSupplierModal }] = useModal();
const [organizationRegModal, { openModal: openOrganizationModal }] = useModal();
const [unitRegModal, { openModal: openUnitModal }] = useModal();
const [materialRegModal, { openModal: openMaterialModal }] = useModal();
//单据类型
function billTypeOpen() {
  openBillTypeModal(true, {
    isUpdate: false,
    showFooter: true,
    tableName:"bus_transfer_storage"
  });
}
//仓库
function warehouseOpen() {
  openWarehouseModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//客户
function customerOpen() {
  openCustomerModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//收货组织
function organizationOpen() {
  openOrganizationModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//供应商
function supplierOpen() {
  openSupplierModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
let index: number | null = null;
//打开选择料品
function handleView(props) {
  index = props.params.$rowIndex;
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

//打开单位选择
function handleUnitView(props) {
  index = props.params.$rowIndex;
  openUnitModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//单据类型回写
function billTypehandleSuccess(val, values) {
  setFieldsValue({
    billTypeName: val[0].label,
    billTypeId: val[0].value,
  });
}
//仓库回写
function warehousehandleSuccess(val, values) {
  setFieldsValue({
    storageWarehouseName: val[0].label,
    storageWarehouseId: val[0].value,
  });
}
//客户回写
function customerhandleSuccess(val, values) {
  setFieldsValue({
    customerName: val[0].label,
    customerId: val[0].value,
  });
}
//供应商回写
function supplierhandleSuccess(val, values) {
  setFieldsValue({
    supplierName: val[0].label,
    supplierId: val[0].value,
  });
}
//收货组织回写
function organizationhandleSuccess(val, values) {
  setFieldsValue({
    storageOrganizationName: val[0].label,
    storageOrganizationId: val[0].value,
  });
}
//料品回写
function materialhandleSuccess(val, values) {
  busMiscellaneousStorageItemTable.dataSource = busMiscellaneousStorageItem.value!.getTableData();
  busMiscellaneousStorageItemTable.dataSource[index].materialName = val[0].label;
  busMiscellaneousStorageItemTable.dataSource[index].materialId = val[0].value;
  busMiscellaneousStorageItemTable.dataSource[index].materialCode = val[0].item.code;
  busMiscellaneousStorageItemTable.dataSource[index].specifications = val[0].item.spec;
  
  // 自动带出单位
  busMiscellaneousStorageItemTable.dataSource[index].unitId = val[0].item.stockUnitId;
  busMiscellaneousStorageItemTable.dataSource[index].unitName = val[0].item.stockUnitName;

}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>